import axios from 'axios';
import ReactDOM from 'react-dom';
import qs from 'qs';
import { message, Spin } from 'antd';


//  设置请求超时时间和域名
axios.defaults.baseURL = '/apiaem';
axios.defaults.timeout = 5 * 60000;
axios.defaults.withCredentials = true;


// 当前正在请求的数量
let requestCount = 0;

// 显示loading
function showLoading() {
  if (requestCount === 0) {
    const dom = document.createElement('div');
    dom.setAttribute('id', 'loading');
    document.body.appendChild(dom);
    let node = <Spin tip="加载中..." size="large" />;
    ReactDOM.render(node, dom);
  }
  requestCount++;
}

// 隐藏loading
function hideLoading() {
  requestCount > 0 && requestCount--;
  if (requestCount === 0 && document.getElementById('loading')) {
    document.body.removeChild(document.getElementById('loading'));
  }
}

//  http request 拦截器
axios.interceptors.request.use(
  (config)  => {
    const { loading } = config;
    if (loading) {
      showLoading();
    }
    if (!config.useSelfDead) {
      config.headers['Content-Type'] = 'application/json;charset=UTF-8';
    }

    // let authorization = sessionStorage.getItem('token');
    // if (authorization && !config.url?.includes('xm')) {
    //   config.headers['x-token-id'] = authorization;
    //   config.headers['app-id'] = '1';
    // }
    return config;
  },
  (err) => {
    if (err.config.headers.isLoading !== false) {
      hideLoading();
    }
    return Promise.reject(err);
  }
);

//  响应拦截器即异常处理
axios.interceptors.response.use(
  (res) => {
    hideLoading();
    let response = res.data;
    const code = Number(response.code) || response.code;
    if (res.config.responseType === 'blob') {
      if (response.size > 1024) {
        return Promise.resolve(res);
      } else {
        if (response.type === 'application/json') {
          response.text().then((res) => {
            const data = JSON.parse(res || '{}');
            message.error(data?.msg ?? '业务逻辑异常');
          });
        } else {
          message.error('业务逻辑异常');
        }
        return Promise.reject(res);
      }
    }
    if (code === 200) {
      return Promise.resolve(response && (response.content ?? response.data));
    } else if (code === 302) {
      return Promise.reject(res);
    } else if (res.status === 200 && code) {
      message.error(response.msg);
      return Promise.reject(res);
    } else if (res.status === 200) {
      return Promise.resolve(res);
    } else {
      return Promise.reject(res);
    }
  },
  (error) => {
    hideLoading();
    if (error && error.response && error.response.data) {
      message.error(error.response.data.msg ? error.response.data.msg : '错误');
    }

    return Promise.reject(error.response);
  }
);

/**
 * 封装get方法
 * @param url
 * @param config
 * @returns {Promise}
 */
function get(url, config) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        ...config,
        // 手动将数组序列化的模式设置为repeat
        paramsSerializer(params) {
          return qs.stringify(params, { arrayFormat: 'repeat' });
        }
      })
      .then((response) => {
        resolve(response);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

/**
 * 封装post请求
 * @param url
 * @param config
 * @returns {Promise}
 */
function post(url, config) {
  const { data, ...rest } = config;
  return new Promise((resolve, reject) => {
    axios
      .post(url, data, {
        ...rest,
        paramsSerializer(params) {
          return qs.stringify(params, { arrayFormat: 'repeat' });
        }
      })
      .then(
        (response) => {
          resolve(response);
        },
        (err) => {
          reject(err);
        }
      );
  });
}

/**
 * 封装patch请求
 * @param url
 * @param config
 * @returns {Promise}
 */
function patch(url, config) {
  return new Promise((resolve, reject) => {
    axios.patch(url, config).then(
      (response) => {
        resolve(response);
      },
      (err) => {
        reject(err);
      }
    );
  });
}

/**
 * 封装put请求
 * @param url
 * @param config
 * @returns {Promise}
 */
function put(url, config) {
  const { data, ...rest } = config;
  return new Promise((resolve, reject) => {
    axios
      .put(url, data, {
        ...rest,
        paramsSerializer(params) {
          return qs.stringify(params, { arrayFormat: 'repeat' });
        }
      })
      .then(
        (response) => {
          resolve(response);
        },
        (err) => {
          reject(err);
        }
      );
  });
}

/**
 * 封装delete请求
 * @param url
 * @param config
 * @returns {Promise}
 */
function del(url, config) {
  return new Promise((resolve, reject) => {
    axios
      .delete(url, config)
      .then((response) => {
        resolve(response);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

//  开放接口
export { get, post, put, patch, del };

export default axios;